package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.MinIOFileTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmMaterialDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.wemedia.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinIOFileTemplate minIOFileTemplate;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult pageQuery(WmMaterialDto wmMaterialDto) {
        //1.参数校验
        if (wmMaterialDto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        wmMaterialDto.checkParam();

        //2，组装查询条件:wrapper
        //2.1 条件1:是否收藏
        //2.2条件2:按创建时间倒序排列
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(wmMaterialDto.getIsCollection() == 1, WmMaterial::getIsCollection, wmMaterialDto.getIsCollection())
                .orderByDesc(WmMaterial::getCreatedTime);
        //3.构建分页Page
        Page page = new Page(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        //4.开启查询
        page(page, wrapper);
        //5.组装结果返回: total list
        PageResponseResult pr = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        pr.setData(page.getRecords());
        return pr;
    }

    /**
     * 素材上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        try {
            //1.将文件上传到minio
            String originalFilename = multipartFile.getOriginalFilename();//a.b.png
            // 1.1处理一下目标文件名，确保唯一性
            String uuid = UUID.randomUUID().toString();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = uuid + suffix;
            String url = minIOFileTemplate.uploadImgFile("", filename, multipartFile.getInputStream());
            //2.将minio返回的图片路径封装成wm_material素材对象
            WmMaterial wmMaterial = new WmMaterial();
            //2.1.填充:url
            wmMaterial.setUrl(url);
            //2.2.填充:user_id   从ThreadLocal中动态获取当前登录用户id
            Integer userId = WmThreadLocalUtil.get();
            wmMaterial.setUserId(userId);
            //2.3.填充:is_collection(默认0，不收藏)
            wmMaterial.setIsCollection((short) 0);
            //2.4.填充:created time
            wmMaterial.setCreatedTime(new Date());
            //3.保存对象到数据库
            save(wmMaterial);
            //4.将ur1返回给前端用作数据回显

            return ResponseResult.okResult(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        if (id == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        WmMaterial wmMaterial = getById(id);
        wmMaterial.setIsCollection((short)1);
        updateById(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 取消收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        if (id == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        WmMaterial wmMaterial = getById(id);
        wmMaterial.setIsCollection((short)0);
        updateById(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }
}

